package com.hunan.api.catv.mq.consumer;


import com.google.gson.JsonObject;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.service.biz.tencent_cloud.sms.SmsBiz;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class SmsConsumer implements RabbitTemplate.ConfirmCallback{

    public static Logger log = LoggerFactory.getLogger(SmsConsumer.class);


    @Autowired
    SmsBiz smsBiz;

    @Autowired
    public SmsConsumer(RabbitTemplate rabbitTemplate) {
        rabbitTemplate.setConfirmCallback(this);
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConstants.sms_queue, durable = "true"), exchange = @Exchange(value = MqConstants.sms_exchange, durable = "true", type = "topic"), key = MqConstants.sms_routingkey))
    public void smsSend(String msg) {
        log.info("[mq收到短信msg：{}]", msg);
        JsonObject msgJson = GsonUtils.fromJson(msg, JsonObject.class);
        try {
            Integer smsType = msgJson.get("smsType").getAsInt();
            String phone = msgJson.get("phone").getAsString();
            ServiceResult sendResult = smsBiz.sendSms(phone, RandomUtils.getRandomNum(6), smsType);
            if (!sendResult.getStatus()) {
                log.error("[SendSms-Error: {}]", sendResult.getMsg());
            }
        } catch (Exception e) {
            log.error("往短信网关发送短信处理失败：", e);
        }


    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("confirm:-[{}]-消息确认成功!!", correlationData != null ? correlationData.getId() : "");
        } else {
            log.info("confirm: -[{}]-消息确认失败:{}", correlationData != null ? correlationData.getId() : "", cause);
        }
    }
}
